package com.usian.jyzx.product.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.usian.common.utils.SmsUtils;
import com.usian.jyzx.model.entity.user.UserInfo;
import com.usian.jyzx.model.vo.common.Result;
import com.usian.jyzx.model.vo.common.ResultCodeEnum;
import com.usian.jyzx.model.vo.h5.LoginUserVo;
import com.usian.jyzx.model.vo.h5.RegisterUserVo;
import com.usian.jyzx.product.service.UserInfoService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 07 09 09 59
 **/
@RestController
@RequestMapping("/api/user")
@Slf4j
@CrossOrigin
public class UserController {


    @PostMapping("/userInfo/login")
    public  Result userInfoLogin(@RequestBody LoginUserVo loginUserVo){
        UserInfo userInfoByUsername = userInfoService.findUserInfoByUsername(loginUserVo.getUsername());
        if(null==userInfoByUsername){
            //return "";
            return Result.build(ResultCodeEnum.NOT_FOUND_USER.getCode(),ResultCodeEnum.NOT_FOUND_USER.getMessage());
        }

        if(!userInfoByUsername.getPassword().equals(loginUserVo.getPassword())){
           // return "";
            return Result.build(ResultCodeEnum.PASSWORD_ERROR.getCode(),ResultCodeEnum.PASSWORD_ERROR.getMessage());
        }

        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("token:"+token, JSON.toJSONString(userInfoByUsername));

        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),token);


    }

    @Autowired
    RedisTemplate redisTemplate;


    // 手机号码的正则表达式
    private static final String PHONE_NUMBER_REGEX = "^1[34578]\\d{9}$";

    /**
     * 校验手机号码是否合法
     *
     * @param phoneNumber 要校验的手机号码
     * @return 如果手机号码合法则返回true，否则返回false
     */
    public static boolean validatePhoneNumber(String phoneNumber) {
        // 创建手机号码正则表达式的模式
        Pattern pattern = Pattern.compile(PHONE_NUMBER_REGEX);
        // 使用模式匹配手机号码
        Matcher matcher = pattern.matcher(phoneNumber);
        // 返回匹配结果
        return matcher.matches();

    }

    /**
     * 业务逻辑:
     * 1: 接受前台传过来的手机号,判断手机号的格式, 判断是否存在
     * 2:生成code(4位/6位) redis(key:手机号;value:code)
     * 3:发送code(短信)
     * 4:响应
     * @param phone
     * @return
     */
  @GetMapping("/sms/sendCode/{phone}")
    public Result sendCode(@PathVariable String phone) throws Exception {
      if (!validatePhoneNumber(phone)){
          return Result.build(ResultCodeEnum.PHONE_ERROR.getCode(),ResultCodeEnum.PHONE_ERROR.getMessage());
      }

      String code = RandomUtil.randomInt(1000, 10000)+"";
      log.info("生成的验证码：{}",code);

      SmsUtils.sendSms(phone,code);

      redisTemplate.opsForValue().set(phone,code);

      log.info("发送验证码：{}",code);

      return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage());



    }

    @Autowired
    UserInfoService userInfoService ;

    /**
     * 1:接受前台传过来的参数[手机号, 验证码,密码, 确认密码,昵称]，，用手机号查询
     * 2:校验验证码(比较:) a:用户输入的验证码  b: redis.get(用户输入的手机号)
     * 3:密码, 确认密码(比较)
     * 4:昵称 (长度)
     * 5: 保存, 删除redis   这个手机号
     * @param registerUserVo
     * @return
     */
    @PostMapping("/userInfo/register")
    public Result register(@RequestBody RegisterUserVo registerUserVo){
        UserInfo userInfo =
                userInfoService.findUserInfoByPhoneNumber(registerUserVo.getUsername());

        if(null!=userInfo){
            return Result.build(ResultCodeEnum.PHONE_HAVE_EXIST.getCode(),ResultCodeEnum.PHONE_HAVE_EXIST.getMessage());
        }

        String code = registerUserVo.getCode();
        log.info("用户输入的code：{}",code);
        String redisCode = (String)redisTemplate.opsForValue().get(registerUserVo.getUsername());
        log.info("redis的code：{}",redisCode);
        if(!code.equals(redisCode)){
            log.info("不一样");
            return Result.build(ResultCodeEnum.CODE_ERROR.getCode(),ResultCodeEnum.CODE_ERROR.getMessage());
        }

        UserInfo userInfoNew = new UserInfo();
        userInfoNew.setUsername(registerUserVo.getUsername());
        userInfoNew.setPassword(registerUserVo.getPassword());
        userInfoNew.setPhone(registerUserVo.getUsername());
        userInfoNew.setNickName(registerUserVo.getNickName());
        userInfoNew.setSex(1);
        userInfoNew.setStatus(1);
        userInfoService.saveUserInfo(userInfoNew);

        redisTemplate.delete(registerUserVo.getUsername());
        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage());

    }

    /**
     * 根据token查询用户信息
     * @return
     */

    @GetMapping("/userInfo/auth/getCurrentUserInfo")
    public  Result authGetCurrentUserInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        log.info("token:{}", token);
        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),userInfo);

    }

}
